package com.aiyige.page.my.favorite.adapter;

import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventFavoriteUnSelect;
import com.aiyige.model.Subject;
import com.aiyige.model.moment.backup.CreatorBackup;
import com.aiyige.model.moment.backup.MediaSummary;
import com.aiyige.model.moment.entity.FavoriteRecord;
import com.aiyige.model.moment.entity.MajorCourse;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.TrainingCourse;
import com.aiyige.model.request.DeleteTaskRequest;
import com.aiyige.model.task.ParamsIds;
import com.aiyige.model.task.Task;
import com.aiyige.page.my.favorite.MyFavoritePage;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiachao on 2017/10/17.
 */

public class MyFavoriteAdapter extends BaseQuickAdapter<FavoriteRecord, BaseViewHolder> {

    RequestOptions circleOptions = RequestOptions.circleCropTransform();
    TrackEvent trackEvent = new TrackEvent();
    private boolean isEdit = false;

    boolean selectAll = false;


    public MyFavoriteAdapter() {
        super(new LinkedList<FavoriteRecord>());
    }


    @Override
    protected void convert(BaseViewHolder helper, FavoriteRecord item) {
        ((MyHolder) helper).bindData(item);
    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder baseViewHolder = new MyHolder(getItemView(R.layout.item_favorite, parent));
        return baseViewHolder;
    }


    public void onViewClicked(FavoriteRecord entity) {
        if (isEdit) {
            entity.setSelected(!entity.isSelected());
            notifyDataSetChanged();
            // 如果全选状态下其中一项手动unselect，那么全选图标设置为unselect
            if (!entity.isSelected()) {
                EventBus.getDefault().post(new EventFavoriteUnSelect());
            }
        } else {
            Moment moment = entity.getMomentBackup();
            if (moment != null && !TextUtils.isEmpty(moment.getRouter())) {
//                String howLong = TrackUtil.getHowLong(moment.getOnsellTime());
//                if (!TextUtils.isEmpty(howLong)) {
//                    HashMap<String, String> hashMap = new HashMap<>();
//                    hashMap.put("time_distance", howLong);
//                    trackEvent.sendEvent(MyApp.getAppContext(), MY_FAVORITE_CONTENT_VIEW_DATE,
//                            MY_FAVORITE_CONTENT_VIEW_DATE_LABEL, hashMap);
//                }
                Router.start(moment.getRouter());
            }
        }
    }


    public class MyHolder extends BaseViewHolder {

        @BindView(R.id.iv_item_selection)
        ImageView ivItemSelection;
        @BindView(R.id.rl_item_selection)
        RelativeLayout rlItemSelection;
        @BindView(R.id.iv_cover)
        ImageView ivCover;
        @BindView(R.id.tv_content_count)
        TextView tvContentCount;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.iv_head)
        ImageView ivHead;
        @BindView(R.id.tv_username)
        TextView tvUsername;
        @BindView(R.id.tv_time)
        TextView tvTime;
        @BindView(R.id.tv_subject_tag)
        TextView tvSubjectTag;
        @BindView(R.id.ll_containerLayout)
        LinearLayout rlContent;
        @BindView(R.id.iv_play)
        ImageView ivPlay;

        @BindView(R.id.fl_video_count_time)
        FrameLayout flVideoCountTime;
        @BindView(R.id.ll_class_valid_info)
        LinearLayout llclassValidInfo;

        @BindView(R.id.iv_class_valid_info_icon)
        ImageView tvClassValidInfoImage;

        @BindView(R.id.tv_class_valid_info)
        TextView tvClassValidInfo;



        public MyHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }


        public void bindData(final FavoriteRecord data) {
            rlItemSelection.setVisibility(isEdit ? View.VISIBLE : View.GONE);
            ivItemSelection.setSelected(data.isSelected());
            Moment momentBackup = null;
//            VideoCourse videoCourse = null;
            boolean visiable = false;
            MediaSummary mediaSummary = null;
            if (data.getMomentBackup() != null) {
                momentBackup = data.getMomentBackup();
                mediaSummary = momentBackup.getMediaSummary();
                if (momentBackup != null && !ListUtil.isEmpty(momentBackup.getCover())) {
                    GlideUtil.with(mContext).big().loadCover(momentBackup.getCover().get(0))
                            .into(ivCover);
                }
                if (mediaSummary != null) {
                    visiable = true;
                    tvContentCount.setVisibility(mediaSummary.getCount() > 0 ? View.VISIBLE : View.INVISIBLE);
                    tvContentCount.setText(mContext.getString(R.string.content_count_value, mediaSummary.getCount() + ""));
                }
                if (data.getMomentSubject().equals(Subject.photo)) {
                    tvContentCount.setVisibility(View.INVISIBLE);
                }
            }
            if (!visiable) {
                tvContentCount.setVisibility(View.INVISIBLE);
            }

            Spanned result;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                result = Html.fromHtml(data.getMomentTitle(), Html.FROM_HTML_MODE_LEGACY);
            } else {
                result = Html.fromHtml(data.getMomentTitle());
            }
            tvTitle.setText(data.isSearch()?result:data.getMomentTitle());
            // 专业课程取得是moreBackup的title
            if (momentBackup != null && momentBackup.getCreatorBackup() != null) {
                CreatorBackup creatorBackup = momentBackup.getCreatorBackup();
                if (creatorBackup.getAvatar() != null) {
                    GlideUtil.with(mContext).small().loadAvatar(creatorBackup.getAvatar()).into(ivHead);
                    tvUsername.setText(creatorBackup.getName());
                }
            }
            rlContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onViewClicked(data);
                }
            });
            rlItemSelection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onViewClicked(data);
                }
            });
            ivItemSelection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onViewClicked(data);
                }
            });
            if (momentBackup != null && momentBackup.getSubject() != null &&
                    (momentBackup.getSubject().equals(Subject.video) || momentBackup.getSubject().equals(Subject.video_course))) {
                flVideoCountTime.setVisibility(View.VISIBLE);
                // 收藏“视频”视频封面下面多显示了时长，应只显示右下角“共n集”，不显示时长，半透明背景只在右下角
//                tvTime.setVisibility(View.VISIBLE);
//                if (mediaSummary != null) {
//                    tvTime.setText(TimeUtils.getDurationTimeForFavorite(mediaSummary.getDuration()));
//                }
                tvSubjectTag.setVisibility(View.INVISIBLE);
                // 只有动态里的普通视频才显示播放按钮
                ivPlay.setVisibility((momentBackup.getSubject().equals(Subject.video)?View.VISIBLE:View.INVISIBLE));

                llclassValidInfo.setVisibility(View.INVISIBLE);
            } else {
//                tvTime.setVisibility(View.INVISIBLE);
                tvSubjectTag.setVisibility(View.INVISIBLE);
                ivPlay.setVisibility(View.INVISIBLE);
                llclassValidInfo.setVisibility(View.VISIBLE);
            }
            // 专业课程
            if (data.getMomentSubject().equals(Subject.major_course)) {
                MajorCourse majorCourse = JsonUtil.toObject(momentBackup.getMoreBackup(),MajorCourse.class);
                if (majorCourse != null) {
                    tvClassValidInfoImage.setVisibility(View.VISIBLE);
                    flVideoCountTime.setVisibility(View.VISIBLE);
                    tvSubjectTag.setVisibility(View.VISIBLE);
                    tvSubjectTag.setText(majorCourse.getClassCount()+mContext.getString(R.string.class_count));
                    tvClassValidInfo.setText(mContext.getString(R.string.class_valid_info_value,majorCourse.getCityName(momentBackup.getCityId()),majorCourse.getStartClassTime()));
                }
            }
            // 培训班
            if (data.getMomentSubject().equals(Subject.training_course)) {
                TrainingCourse trainingCourse = JsonUtil.toObject(momentBackup.getMoreBackup(),TrainingCourse.class);
                if (trainingCourse != null) {
                    tvClassValidInfoImage.setVisibility(View.VISIBLE);
                    flVideoCountTime.setVisibility(View.VISIBLE);
                    tvSubjectTag.setVisibility(View.VISIBLE);
                    tvSubjectTag.setText(trainingCourse.getClassCount()+mContext.getString(R.string.class_count));
                    tvClassValidInfo.setText(mContext.getString(R.string.class_valid_info_value,trainingCourse.getCityName(),trainingCourse.getStartClassTime()));
                }
            }





        }
    }




    public void setEdit(boolean edit) {
        isEdit = edit;
        if (!isEdit) {
            unSelectAll();
        }
        notifyDataSetChanged();
    }

    public void selectAll() {
        List<FavoriteRecord> list = getData();
        if (list == null || list.isEmpty()) {
            return;
        }
        for (FavoriteRecord entity : list) {
            entity.setSelected(true);
        }
        notifyDataSetChanged();
    }

    public void unSelectAll() {
        List<FavoriteRecord> list = getData();
        if (list == null || list.isEmpty()) {
            return;
        }
        for (FavoriteRecord entity : list) {
            entity.setSelected(false);
        }
        notifyDataSetChanged();
    }

    public List<FavoriteRecord> getSelectedList() {
        List<FavoriteRecord> list = getData();
        if (list == null || list.isEmpty()) {
            return null;
        }
        List<FavoriteRecord> selectedList = new ArrayList<>();
        for (FavoriteRecord entity : list) {
            if (entity.isSelected()) {
                selectedList.add(entity);
            }
        }
        return selectedList;
    }

    public void deleteSelected() {

        List<String> goodsIds = new ArrayList<>();
        ParamsIds paramsIds = new ParamsIds();
        for (FavoriteRecord entity : getSelectedList()) {
            goodsIds.add(entity.getId());
        }
        paramsIds.setIds(goodsIds);
        showDialog();
        Task task = Task.newBuilder().name(Task.batchDeleteSomeFavoriteRecords).params(paramsIds).build();
        DeleteTaskRequest.newBuilder().task(task).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                dismissDialog();
                try {
                    if (response.isSuccessful()) {
                        delete();
                        ToastX.show(mContext.getString(R.string.delete_success));
                    }
                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                dismissDialog();
                if (!TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    private void showDialog() {
        ((BaseActivity) mContext).showLoading();
    }

    private void dismissDialog() {
        ((BaseActivity) mContext).hideLoading();
    }

    public void delete() {
        List<FavoriteRecord> list = getData();
        if (list == null || list.isEmpty() || getSelectedList() == null
                || getSelectedList().isEmpty()) {
            ToastX.show(MyApp.getAppContext().getString(R.string.please_select_favorite_data));
            return;
        }
        list.removeAll(getSelectedList());
        notifyDataSetChanged();
        if (list == null || list.isEmpty()) {
            ((MyFavoritePage) mContext).setEdit(false);
        }
    }

}
